package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.tanhua.domain.Analysis;
import com.itheima.tanhua.enums.LogType;
import com.itheima.tanhua.vo.AnalysisSummaryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Lff
 * @date 2022/4/7
 */
@Service
public class DashboardService {

    @Autowired
    private AnalysisService analysisService;

    /**
     * 概要信息
     *
     * @return
     */
    public AnalysisSummaryVo summary() {
        //查询今天的统计数据

        Analysis today = analysisService.getAnalysisByDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));


        //查询昨天的统计数据
        Analysis yesterday = analysisService.getAnalysisByDate(DateUtil.yesterday().toString("yyyy-MM-dd"));

        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal newUsersTodayRate = cal(today.getNumRegistered(), yesterday.getNumRegistered());
        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal loginTimesTodayRate = cal(today.getNumLogin(), yesterday.getNumLogin());
        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal activeUsersTodayRate = cal(today.getNumActive(), yesterday.getNumActive());

        //累计用户数  累计注册用户
        Long cumulativeUsers = analysisService.countRegister(null, null);

        //过去30天用户活跃数
        String t1 = DateUtil.today();
        String month = DateUtil.lastMonth().toString("yyyy-MM-dd");
        Long activePassMonth = analysisService.countActiveByDate(month, t1);

        //过去七天用户活跃数
        String week = DateUtil.lastWeek().toString("yyyy-MM-dd");
        Long activePassWeek = analysisService.countActiveByDate(week, t1);

        //填充数据
        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();

        analysisSummaryVo.setCumulativeUsers(cumulativeUsers);
        analysisSummaryVo.setActivePassMonth(activePassMonth);
        analysisSummaryVo.setActivePassWeek(activePassWeek);
        analysisSummaryVo.setNewUsersToday(Long.valueOf(today.getNumLogin()));
        analysisSummaryVo.setNewUsersTodayRate(newUsersTodayRate);
        analysisSummaryVo.setLoginTimesToday(Long.valueOf(today.getNumLogin()));
        analysisSummaryVo.setLoginTimesTodayRate(loginTimesTodayRate);
        analysisSummaryVo.setActiveUsersToday(Long.valueOf(today.getNumActive()));
        analysisSummaryVo.setActiveUsersTodayRate(activeUsersTodayRate);

        return analysisSummaryVo;
    }

    /**
     * 计算各种百分值
     *
     * @param today
     * @param yesterday
     * @return
     */
    private BigDecimal cal(Integer today, Integer yesterday) {
        BigDecimal t1 = new BigDecimal(today);
        BigDecimal t2 = new BigDecimal(yesterday);
        BigDecimal result = t1.subtract(t2).divide(t2);
        return result;
    }
}
